package com.qsxc.system.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qsxc.constants.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * redis 缓存配置，仅当配置文件中spring.cache.type = redis时生效
 *
 * @author
 */
@Slf4j
@EnableCaching
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return (o, method, objects) -> o.getClass().getSimpleName() +
                "." +
                method.getName() +
                "[" +
                StringUtils.arrayToCommaDelimitedString(objects) +
                "]";
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        template.setKeySerializer(stringRedisSerializer());
        template.setHashKeySerializer(stringRedisSerializer());
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer());
        template.setValueSerializer(genericJackson2JsonRedisSerializer());

        template.afterPropertiesSet();
        return template;
    }


    @Bean
    public DefaultRedisScript<Long> limitScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(limitScriptText());
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    /**
     * 限流脚本
     */
    private String limitScriptText() {
        return "local key = KEYS[1]\n" +
                "local count = tonumber(ARGV[1])\n" +
                "local time = tonumber(ARGV[2])\n" +
                "local current = redis.call('get', key);\n" +
                "if current and tonumber(current) > count then\n" +
                "    return tonumber(current);\n" +
                "end\n" +
                "current = redis.call('incr', key)\n" +
                "if tonumber(current) == 1 then\n" +
                "    redis.call('expire', key, time)\n" +
                "end\n" +
                "return tonumber(current);";
    }


    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.MINUTE5_EXPIRE_TIME))
                .withInitialCacheConfigurations(this.getRedisCacheConfigurationMap())
                .transactionAware()
                .build();
    }

    private StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    private GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer() {
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        return new GenericJackson2JsonRedisSerializer(om);
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(long seconds) {
        return RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(name -> name + ":")
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer()))
                .serializeValuesWith(
                        RedisSerializationContext
                                .SerializationPair
                                .fromSerializer(genericJackson2JsonRedisSerializer())
                ).entryTtl(Duration.ofSeconds(seconds));
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.SECONDS10, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.SECONDS10_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.SECOND30, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.SECONDS30_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.MINUTE1, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.MINUTE1_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.MINUTE2, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.MINUTE2_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.MINUTE3, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.MINUTE3_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.MINUTE10, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.MINUTE10_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.MINUTE30, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.MINUTE30_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.FUCTION, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.HOUR20_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.DEFAULT, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.DEFAULT_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.DAY1, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.DAY1_EXPIRE_TIME));
        redisCacheConfigurationMap.put(RedisConstant.CacheNames.USERS, this.getRedisCacheConfigurationWithTtl(RedisConstant.CacheExpireTime.DAY1_EXPIRE_TIME));
        return redisCacheConfigurationMap;
    }

}
